<?php
  list($usec, $sec) = microtime();
  $serverTime = $sec * 1000 + round($usec * 1000);
  
  $config = array();
  require('_config.php');

  //read params
  if (isset($_POST['data'])) {
    $data = $_POST['data'];
    $hash = $_POST['hash'];
    $clientTime = $_POST['clientTime'];
  } else if (isset($_GET['data'])) {
    $data = $_GET['data'];
    $hash = $_GET['hash'];
    $clientTime = $_GET['clientTime'];
  } else exit('0');
  
  $timeOffset = $serverTime - $clientTime;
  
  //source verification
  if ($hash != sha1($config['domain'].$data.$config['key'])) exit(0);
    
  //save data to DB
  $filename = $config['dbdir'].'/'.date('Y-m-d').'.sq3';//separate DB for each day
  $init = !file_exists($filename);

  try {
    $db = new SQLite3($filename);

    if ($init) {
      $db->exec('create table if not exists datapkgs (serverTime INTEGER not null, clientTime INTEGER not null, timeOffset INTEGER not null, data BLOB)');
    }
    $st = $db->prepare('insert into datapkgs (timeOffset, serverTime, clientTime, data) values (:timeOffset, :serverTime, :clientTime, :data)');
    $st->bindValue('timeOffset', $timeOffset, SQLITE3_INTEGER);
    $st->bindValue('serverTime', $serverTime, SQLITE3_INTEGER);
    $st->bindValue('clientTime', $clientTime, SQLITE3_INTEGER);
    $st->bindValue('data', $data, SQLITE3_BLOB);//SQLITE3_NULL
    $st->execute();
    $st->close();
    $db->close();
    exit(1);
  } catch (Exception $e) {
    echo 'Failed: ' . $e->getMessage();
    try {
      $db->close();
    } catch (Exception $ee) {
      //
    }
  }
?>